package com.fancy.music.controller.admin;

import com.fancy.common.dto.PageResult;
import com.fancy.common.dto.response.Result;
import com.fancy.music.entity.Song;
import com.fancy.music.service.SongService;
import com.fancy.music.util.FileUploadUtil;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Api(tags = "管理员-歌曲管理")
@RestController
@RequestMapping("/api/v1/admin/songs")
@RequiredArgsConstructor
public class AdminSongController {

    private final SongService songService;
    private final FileUploadUtil fileUploadUtil;

    @ApiOperation(value = "获取歌曲管理列表", notes = "管理员查看所有歌曲，包括待审核的歌曲")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "keyword", value = "搜索关键词", paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "genre", value = "音乐风格", paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "auditStatus", value = "审核状态(0-待审核,1-通过,2-拒绝)", paramType = "query", dataType = "int"),
        @ApiImplicitParam(name = "status", value = "状态(0-禁用,1-正常)", paramType = "query", dataType = "int"),
        @ApiImplicitParam(name = "page", value = "页码", paramType = "query", dataType = "int", example = "1"),
        @ApiImplicitParam(name = "size", value = "每页大小", paramType = "query", dataType = "int", example = "20")
    })
    @GetMapping
    public Result<PageResult<Song>> getSongManageList(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String genre,
            @RequestParam(required = false) Integer auditStatus,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {
        PageResult<Song> result = songService.searchSongs(keyword, genre, null, null, page, size);
        return Result.success(result);
    }

    @ApiOperation(value = "创建歌曲", notes = "管理员创建新歌曲")
    @ApiParam(name = "song", value = "歌曲信息", required = true)
    @PostMapping
    public Result<Long> createSong(@RequestBody Song song) {
        Long songId = songService.createSong(song);
        if (songId != null) {
            return Result.success(songId);
        } else {
            return Result.fail("创建歌曲失败");
        }
    }

    @ApiOperation(value = "上传歌曲文件", notes = "上传歌曲音频文件、封面图片和歌词文件")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "songId", value = "歌曲ID", required = true, paramType = "path", dataType = "long"),
        @ApiImplicitParam(name = "audioFile", value = "音频文件", paramType = "form", dataType = "file"),
        @ApiImplicitParam(name = "coverFile", value = "封面图片", paramType = "form", dataType = "file"),
        @ApiImplicitParam(name = "lyricFile", value = "歌词文件", paramType = "form", dataType = "file")
    })
    @PostMapping("/{songId}/upload")
    public Result<Void> uploadSongFiles(
            @PathVariable Long songId,
            @RequestParam(required = false) MultipartFile audioFile,
            @RequestParam(required = false) MultipartFile coverFile,
            @RequestParam(required = false) MultipartFile lyricFile) {

        try {
            Song song = songService.getSongDetail(songId);
            if (song == null) {
                return Result.fail("歌曲不存在");
            }

            Song updateSong = new Song();
            updateSong.setSongId(songId);

            // 上传音频文件
            if (audioFile != null && !audioFile.isEmpty()) {
                // 检查文件大小（限制50MB）
                if (!fileUploadUtil.isFileSizeValid(audioFile, 50)) {
                    return Result.fail("音频文件大小不能超过50MB");
                }

                String audioPath = fileUploadUtil.uploadAudioFile(audioFile);
                updateSong.setFileUrl(audioPath);
                updateSong.setFileSize(fileUploadUtil.getFileSize(audioFile));

                // 获取文件格式
                String originalFilename = audioFile.getOriginalFilename();
                if (originalFilename != null) {
                    String format = originalFilename.substring(originalFilename.lastIndexOf('.') + 1);
                    updateSong.setFormat(format);
                }
            }

            // 上传封面图片
            if (coverFile != null && !coverFile.isEmpty()) {
                // 检查文件大小（限制5MB）
                if (!fileUploadUtil.isFileSizeValid(coverFile, 5)) {
                    return Result.fail("封面图片大小不能超过5MB");
                }

                String coverPath = fileUploadUtil.uploadCoverImage(coverFile);
                updateSong.setCoverUrl(coverPath);
            }

            // 上传歌词文件
            if (lyricFile != null && !lyricFile.isEmpty()) {
                // 检查文件大小（限制1MB）
                if (!fileUploadUtil.isFileSizeValid(lyricFile, 1)) {
                    return Result.fail("歌词文件大小不能超过1MB");
                }

                String lyricPath = fileUploadUtil.uploadLyricFile(lyricFile);
                updateSong.setLyricUrl(lyricPath);
            }

            // 更新歌曲信息
            boolean success = songService.updateSong(updateSong);
            if (success) {
                return Result.success(null);
            } else {
                return Result.fail("更新歌曲文件信息失败");
            }

        } catch (Exception e) {
            return Result.fail("文件上传失败: " + e.getMessage());
        }
    }

    @ApiOperation(value = "创建歌曲并上传文件", notes = "一次性创建歌曲并上传相关文件")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "songName", value = "歌曲名称", required = true, paramType = "form", dataType = "string"),
        @ApiImplicitParam(name = "artistId", value = "歌手ID", required = true, paramType = "form", dataType = "long"),
        @ApiImplicitParam(name = "albumId", value = "专辑ID", paramType = "form", dataType = "long"),
        @ApiImplicitParam(name = "genre", value = "音乐风格", paramType = "form", dataType = "string"),
        @ApiImplicitParam(name = "language", value = "语言", paramType = "form", dataType = "string"),
        @ApiImplicitParam(name = "isVip", value = "是否VIP歌曲", paramType = "form", dataType = "int"),
        @ApiImplicitParam(name = "audioFile", value = "音频文件", required = true, paramType = "form", dataType = "file"),
        @ApiImplicitParam(name = "coverFile", value = "封面图片", paramType = "form", dataType = "file"),
        @ApiImplicitParam(name = "lyricFile", value = "歌词文件", paramType = "form", dataType = "file")
    })
    @PostMapping("/create-with-files")
    public Result<Long> createSongWithFiles(
            @RequestParam String songName,
            @RequestParam Long artistId,
            @RequestParam(required = false) Long albumId,
            @RequestParam(required = false) String genre,
            @RequestParam(required = false) String language,
            @RequestParam(defaultValue = "0") Integer isVip,
            @RequestParam MultipartFile audioFile,
            @RequestParam(required = false) MultipartFile coverFile,
            @RequestParam(required = false) MultipartFile lyricFile) {

        try {
            // 检查必需的音频文件
            if (audioFile == null || audioFile.isEmpty()) {
                return Result.fail("音频文件不能为空");
            }

            // 检查文件大小
            if (!fileUploadUtil.isFileSizeValid(audioFile, 50)) {
                return Result.fail("音频文件大小不能超过50MB");
            }

            if (coverFile != null && !coverFile.isEmpty() && !fileUploadUtil.isFileSizeValid(coverFile, 5)) {
                return Result.fail("封面图片大小不能超过5MB");
            }

            if (lyricFile != null && !lyricFile.isEmpty() && !fileUploadUtil.isFileSizeValid(lyricFile, 1)) {
                return Result.fail("歌词文件大小不能超过1MB");
            }

            // 上传文件
            String audioPath = fileUploadUtil.uploadAudioFile(audioFile);
            String coverPath = null;
            String lyricPath = null;

            if (coverFile != null && !coverFile.isEmpty()) {
                coverPath = fileUploadUtil.uploadCoverImage(coverFile);
            }

            if (lyricFile != null && !lyricFile.isEmpty()) {
                lyricPath = fileUploadUtil.uploadLyricFile(lyricFile);
            }

            // 创建歌曲对象
            Song song = new Song();
            song.setSongName(songName);
            song.setArtistId(artistId);
            song.setAlbumId(albumId);
            song.setGenre(genre);
            song.setLanguage(language);
            song.setIsVip(isVip);
            song.setFileUrl(audioPath);
            song.setCoverUrl(coverPath);
            song.setLyricUrl(lyricPath);
            song.setFileSize(fileUploadUtil.getFileSize(audioFile));

            // 获取音频文件格式
            String originalFilename = audioFile.getOriginalFilename();
            if (originalFilename != null) {
                String format = originalFilename.substring(originalFilename.lastIndexOf('.') + 1);
                song.setFormat(format);
            }

            // 创建歌曲
            Long songId = songService.createSong(song);
            if (songId != null) {
                return Result.success(songId);
            } else {
                // 创建失败，删除已上传的文件
                fileUploadUtil.deleteFile(audioPath);
                if (coverPath != null) {
                    fileUploadUtil.deleteFile(coverPath);
                }
                if (lyricPath != null) {
                    fileUploadUtil.deleteFile(lyricPath);
                }
                return Result.fail("创建歌曲失败");
            }

        } catch (Exception e) {
            return Result.fail("创建歌曲失败: " + e.getMessage());
        }
    }

    @ApiOperation(value = "更新歌曲信息", notes = "管理员修改歌曲信息")
    @ApiImplicitParam(name = "songId", value = "歌曲ID", required = true, paramType = "path", dataType = "long")
    @ApiParam(name = "song", value = "歌曲信息", required = true)
    @PutMapping("/{songId}")
    public Result<Void> updateSong(@PathVariable Long songId, @RequestBody Song song) {
        song.setSongId(songId);
        boolean success = songService.updateSong(song);
        if (success) {
            return Result.success(null);
        } else {
            return Result.fail("更新歌曲失败");
        }
    }

    @ApiOperation(value = "删除歌曲", notes = "管理员删除指定歌曲")
    @ApiImplicitParam(name = "songId", value = "歌曲ID", required = true, paramType = "path", dataType = "long")
    @DeleteMapping("/{songId}")
    public Result<Void> deleteSong(@PathVariable Long songId) {
        boolean success = songService.deleteSong(songId);
        if (success) {
            return Result.success(null);
        } else {
            return Result.fail("删除歌曲失败");
        }
    }

    @ApiOperation(value = "批量删除歌曲", notes = "管理员批量删除多个歌曲")
    @ApiParam(name = "songIds", value = "歌曲ID列表", required = true)
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteSongs(@RequestBody List<Long> songIds) {
        int successCount = 0;
        for (Long songId : songIds) {
            if (songService.deleteSong(songId)) {
                successCount++;
            }
        }
        if (successCount > 0) {
            return Result.success(null);
        } else {
            return Result.fail("批量删除失败");
        }
    }

    @ApiOperation(value = "审核歌曲", notes = "管理员审核歌曲，设置审核状态")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "songId", value = "歌曲ID", required = true, paramType = "path", dataType = "long"),
        @ApiImplicitParam(name = "auditStatus", value = "审核状态(1-通过,2-拒绝)", required = true, paramType = "query", dataType = "int"),
        @ApiImplicitParam(name = "auditRemark", value = "审核备注", paramType = "query", dataType = "string")
    })
    @PutMapping("/{songId}/audit")
    public Result<Void> auditSong(
            @PathVariable Long songId,
            @RequestParam Integer auditStatus,
            @RequestParam(required = false) String auditRemark) {
        boolean success = songService.auditSong(songId, auditStatus, auditRemark);
        if (success) {
            return Result.success(null);
        } else {
            return Result.fail("审核歌曲失败");
        }
    }
}
